#include "queue.h"

/** 
*@brief 环形队列初始化函数. 
*@param 
*   - *handle 操作句柄.
*   - *buf    缓冲区地址. 
*   - size    缓冲区大小.
*
*@return void 
 */
void Queue_Init(RingBuffer_t *handle, uint8_t *buf, uint16_t _size)
{
    handle->Read = 0;
    handle->Write = 0;
    handle->Size = _size;
    handle->Source = buf;
}

/**
*@brief 数据入队函数，OVER_WRITE决定当.
*       队列满时是否支持从头覆盖写入.
*@param 
*   - *handle 操作句柄.
*   - *byte   写入的字节.
*
*@return 
*   - QUEUE_OK   入队成功.
*   - QUEUE_FAIL 队列已满，入队失败.
*/
err_code_t Queue_Push(RingBuffer_t *handle, uint8_t byte)
{
#if !OVER_WRITE
    if((handle->Write + 1) % handle->Size == handle->Read)
        return QUEUE_FAIL;
#endif
    handle->Source[handle->Write] = byte;
    handle->Write = (handle->Write + 1) % handle->Size;
    return QUEUE_OK;
}

/**
*@brief 数据出队函数.
*@param 
*   - *handle 操作句柄.
*   - *byte   读出数据存放的地址.
*
*@return 
*   - QUEUE_OK   出队成功.
*   - QUEUE_FAIL 队列为空，出队失败.
*/
err_code_t Queue_Pop(RingBuffer_t *handle, uint8_t *byte)
{
    if(handle->Read == handle->Write)
        return QUEUE_FAIL;
    *byte = handle->Source[handle->Read];
    handle->Read = (handle->Read + 1) % handle->Size;
    return QUEUE_OK;
}

/**
*@brief 数据全部出队函数.
*@param 
*   - *handle 操作句柄.
*   - *buf    读出数据存放的数组.
*
*@return 
*   - byteCnt 数据长度.
*/
uint16_t Queue_PopAll(RingBuffer_t *handle, uint8_t *buf)
{
    uint16_t byteCnt = 0;
    while(Queue_Pop(handle, buf++) == QUEUE_OK)
        byteCnt++;
    
    return byteCnt;
}

err_code_t QueueIsEmpty(RingBuffer_t *handle)
{
    if(handle->Read == handle->Write)
        return QUEUE_OK; 
    else
        return QUEUE_FAIL;
}

